SUCCESS = 200;
ERROR = 500;
BUSY = 101;
INVALID_PARAM = 102;
NO_PERMISSION = 103;
USER_NOT_LOGIN = 104;

USERNAME_EXIST = 4001;
USERNAME_PASSWORD_WRONG = 4002;
VERIFY_CODE_INVALID = 5001;
VERIFY_CODE_WRONG = 5002;

axios.defaults.withCredentials = true;

function request(url, type, data) {
    type = type.toLowerCase();
    let getOrDelete = type === "get" || type === "delete";
    let postOrPut = type === "post" || type === "put";
    return axios({
        url: url,
        method: type,
        params: (data && getOrDelete) ? data : null,
        data: (data && postOrPut) ? data : null,
        paramsSerializer: params => {
            return Qs.stringify(params, {indices: false})
        }
    })
}

axios.interceptors.response.use(
    response => {
        if (response.status === 200) {
            switch (response.data.code) {
                case SUCCESS:
                    return Promise.resolve(response.data.data);
                case ERROR:
                    location.href = "500.html";
                    break;
                case USER_NOT_LOGIN:
                    location.href = "login.html";
                    break;
                case INVALID_PARAM:
                case NO_PERMISSION:
                    location.href = "404.html";
                    break;
                case BUSY:
                    alert(response.data.msg);
                    location.reload();
                    break;
                case USERNAME_EXIST:
                case USERNAME_PASSWORD_WRONG:
                case VERIFY_CODE_INVALID:
                case VERIFY_CODE_WRONG:
                    break;
                default:
                    if (response.data.msg)
                        alert(response.data.msg);
            }
            return Promise.reject({
                code: response.data.code,
                msg: response.data.msg
            });
        }
    }
);
